package com.xxl.servlet;

import com.xxl.bean.Classes;
import com.xxl.services.ClassesService;
import com.xxl.services.impl.ClassesServiceImpl;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("*.classes")
public class ClassesServlet extends HttpServlet {
    ClassesService scService = new ClassesServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        ServletContext servletContext = req.getServletContext();
        String path = (String) servletContext.getAttribute("path");
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String servletPath = req.getServletPath();
        String reqName = servletPath.split("\\.")[0].split("/")[1];
        if ("addOrUpdate".equals(reqName)){
            String classesId = req.getParameter("classesId");
            String classesName = req.getParameter("classesName");
            scService.addOrUpdate(classesId,classesName);

        }else if ("delete".equals(reqName)){
            String vs = req.getParameter("vs");
            String classesId = vs.split("Classes\\{classesId=")[1].split(",")[0];
            boolean flag = scService.delByClassesId(Integer.parseInt(classesId));
            if (flag){
                resp.getWriter().println("删除成功");
            }else {
                resp.getWriter().println("删除失败");
            }
        }
        List<Classes> list = new ArrayList<>();
        try {
            scService.listAddClasses(list);
        } catch (SQLException throwables) {
            System.out.println(throwables);
        }
        req.setAttribute("classes",list);
        req.getRequestDispatcher(path).forward(req,resp);
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req,resp);
    }
}
